# -*- coding: utf-8 -*-
# -----------------------------------------
# @Time       : 2018/6/18 13:54
# @Author     : dqz 
# @Email      : 1406990390@qq.com
# @File       : api.py
# @Software   : PyCharm
# -----------------------------------------
import json

from flask import Blueprint, request, jsonify

from .sh_tools import sync_data, sync_schema, sync_data_by_where, sync_data_schema, sync_data_schema_by_where

sync = Blueprint("sync", __name__, url_prefix="/db/sync")


@sync.route("/table_schema", methods=("POST",))
def table_schema():
    params = json.loads(request.get_data(as_text=True))
    infos = {
        "status": False,
        "msg": ""
    }
    try:
        src = params["src"]
        dest = params["dest"]
        infos = sync_schema(src, dest)
    except Exception as e:
        infos["msg"] = f"src and dest is needed! {e}"

    return jsonify(infos)


@sync.route("/table_data", methods=("POST",))
def table_data():
    params = json.loads(request.get_data(as_text=True))
    infos = {
        "status": False,
        "msg": ""
    }
    try:
        src = params["src"]
        dest = params["dest"]
        infos = sync_data(src, dest)
    except Exception as e:
        infos["msg"] = f"src and dest is needed! {e}"

    return jsonify(infos)


@sync.route("/table_schema_and_data", methods=("POST",))
def table_schema_and_data():
    params = json.loads(request.get_data(as_text=True))
    infos = {
        "status": False,
        "msg": ""
    }
    try:
        src = params["src"]
        dest = params["dest"]
        infos = sync_data_schema(src, dest)
    except Exception as e:
        infos["msg"] = f"src and dest is needed! {e}"

    return jsonify(infos)


@sync.route("/table_data_by_where", methods=("POST",))
def table_data_by_where():
    params = json.loads(request.get_data(as_text=True))
    infos = {
        "status": False,
        "msg": ""
    }
    try:
        src = params["src"]
        dest = params["dest"]
        where = params["where"]
        infos = sync_data_by_where(src, dest, where)
    except Exception as e:
        infos["msg"] = f"src and dest and where is needed! {e}"

    return jsonify(infos)


@sync.route("/table_schema_and_data_by_where", methods=("POST",))
def table_data_schema_by_where():
    params = json.loads(request.get_data(as_text=True))
    infos = {
        "status": False,
        "msg": ""
    }
    try:
        src = params["src"]
        dest = params["dest"]
        where = params["where"]
        infos = sync_data_schema_by_where(src, dest, where)
    except Exception as e:
        infos["msg"] = f"src and dest is needed! {e}"

    return jsonify(infos)
